package com.lujieni.netty.advanced;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

import java.nio.charset.Charset;

public class TestLengthFieldBasedFrameDecoder {


    public static void main(String[] args) {
        EmbeddedChannel channel = new EmbeddedChannel(new LengthFieldBasedFrameDecoder(1024, 0, 4, 0, 4)
                ,new ChannelInboundHandlerAdapter(){
            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                ByteBuf byteBuf = (ByteBuf) msg;
                System.out.println(byteBuf.toString(Charset.defaultCharset()));
            }
        });

        ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer();
        m1(buffer, "hello, world");
        m1(buffer, "fuck");

        channel.writeInbound(buffer);

    }

    private static void m1(ByteBuf buffer, String cc) {
        buffer.writeInt(cc.getBytes().length);
        buffer.writeBytes(cc.getBytes());
    }


}
